<?php

namespace App\Http\Controllers\backend;

use App\Models\Book;
use Illuminate\Support\Facades\Input;
use App\Models\Category;
use Illuminate\Support\Facades\Redirect;
use App\Models\Operation;

class BookController extends BaseController {
	
	public function index() {
		$categories = Category::pluck('name', 'id');
		$books = Book::select(['id', 'name', 'thumbnail', 'category_id', 'author', 'abstract', 'status', 'href']);
		if(!is_null(Input::get('category_id'))) {
			$books = $books->where('category_id', Input::get('category_id'));
		}
		if(!is_null(Input::get('name'))) {
			$books = $books->where('name', 'like', '%'.Input::get('name').'%');
		}
		if(!is_null(Input::get('author'))) {
			$books = $books->where('author', 'like', '%'.Input::get('author').'%');
		}
		$books = $books->paginate(100);
		return view('backend.books', compact('books', 'categories'));
	}
	
	public function edit($id) {
		$book = Book::find($id);
		$categories = Category::pluck('name', 'id');
		return view('backend.book_form', compact('book', 'categories'));
	}
	
	public function update($id) {
		$book = Book::find($id);
		$input = Input::all();
		$validation = validator($input, Book::$rules, Book::$msgs);
		if($validation->passes()) {
			if(isset($input['thumbnail'])) {
				if($book->thumbnail != 'nocover.jpg') {
					@unlink(public_path('uploads/covers/'. $book->thumbnail ));
				}
				$input['thumbnail']->move(public_path('uploads/covers'), $book->id.'-cover.jpg');
				$input['thumbnail'] = $book->id.'-cover.jpg';
			}
			$book->update($input);
			Operation::create([
				'action' => '编辑小说',
				'content' => '修改了小说《' . $book->name . '》的资料',
			]);
		}
		
		return Redirect::back()
			->withInput()
			->withErrors($validation);
	}
	
	public function destroy($id) {
		$book = Book::find($id);
		if(count($book->sections) > 0) {
			foreach ($book->sections as $section) {
				$section->delete();
			}
		}
		Operation::create([
			'action' => '删除小说',
			'content' => '修改了小说《' . $book->name . '》',
		]);
		$book->delete();
		return Redirect::back();
	}
	
	public function recover() {
		$ids = Input::get('ids');
		foreach ($ids as $id) {
			$book = Book::find($id);
			$book->recover = true;
			$book->save();
			unset($book);
		}
		return redirect('backend/books');
	}

}
